import { get_chains } from '@/services/pages';
import { get_user_info } from '@/services/user';
import { action, makeObservable, observable } from 'mobx';
import { get_stores } from '../services/pages';
// import { timInit } from '@/components/tim/tim';
import { get_user_sign } from '../services/user';
import TIM from 'tim-js-sdk';

/*
 * @Author: your name
 * @Date: 2021-04-19 15:40:44
 * @LastEditTime: 2021-05-30 18:25:46
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /admin/src/pages/globalModel.ts
 */

interface IUserInfo {
  admin_id: number;
  chain_id: number;
  create_time: string;
  is_boss: number;
  is_delete: number;
  is_super: number;
  password: string;
  store_id: number;
  update_time: string;
  username: string;
  box_id: number;
}
const SDKAPPID = 1400453671;
export const tim = TIM.create({
  SDKAppID: SDKAPPID,
});

class GlobalModel {
  constructor() {
    // 添加makeObservable
    makeObservable(this);
  }
  @observable userInfo: IUserInfo | null = null;
  @observable chainList: { chain_id: number; chain_name: string }[] = [];
  @observable storeList: { store_id: number; store_name: string }[] = [];
  @observable receivedMsg: { type: string; message: string } | null = null;
  @observable receive = null;

  timInit = async (userID: string, userSig: string) => {
    tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
    let promise = tim.login({ userID: userID, userSig: userSig });
    promise
      .then((imResponse: any) => {
        console.log(imResponse.data, 'imResponse===='); // 登录成功
        this.bindEvents();
        if (imResponse.data.repeatLogin === true) {
          // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
          console.log(imResponse.data.errorInfo);
        }
      })
      .catch((imError: any) => {
        console.warn('login error==:', imError); // 登录失败的相关信息
      });
  };

  bindEvents = () => {
    tim.on(TIM.EVENT.MESSAGE_RECEIVED, (event: any) => {
      this.receivedMsg = JSON.parse(event.data[0].payload.text);
      this.receive = Symbol();
      console.log('this.receivedMsg.data===', this.receivedMsg);
    });
  };

  TimLogout = () => {
    let promise = tim.logout();
    promise
      .then(function (imResponse) {
        console.log(imResponse.data, '// 登出成功'); // 登出成功
      })
      .catch(function (imError) {
        console.warn('logout error:', imError);
      });
  };

  @action
  getUserInfo = async () => {
    const res = await get_user_info();
    this.userInfo = res.data.results;
  };

  getUserSign = async () => {
    const res = await get_user_sign();
    console.log(res, 'userSign=');

    this.timInit(res.data.results.accountId, res.data.results.userSign);
  };

  getChains = () => {
    get_chains().then((res) => {
      this.chainList = res.data.results;
    });
  };

  getStores = () => {
    get_stores().then((res) => {
      this.storeList = res.data.results;
    });
  };
}

export const globalModel = new GlobalModel();
